<?php

namespace app\api\controller\ai;

use app\admin\model\ai\Config as ConfigModel;
use thinkct\controller\Frontend;
use app\common\model\ai\draw\Content as drawContentModel;
use draw\Yjai;
use thinkct\library\DrawAI;
use app\common\facade\ai\UserVip;

class Draw extends Frontend
{
    protected array $noNeedLogin = ['get_image', 'get_list', 'get_style'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function submit(): void
    {
        $draw_type = $this->request->post('draw_type');
        $content = $this->request->post('content');
        if (empty($content)) $this->error('内容不能为空');
        $prompt = $content;


        $draw_price = ConfigModel::where('name', 'draw_price')->value('value') ?? '0.01';

        // 判断是否为会员
        if (UserVip::isVip($this->auth->id)) {
            UserVip::addRecord($this->auth->id, 'draw', 1, '绘画消费');
        } else {
            // 获取用户余额
            if($this->auth->money < $draw_price) {
                $this->error('余额不足，请充值');
            }
            // 扣除用户余额
            $user = \app\common\model\User::where('id', $this->auth->id)->find();
            $user->money = $user->money - $draw_price;
            $user->save();
            \app\common\model\UserMoneyLog::create([
                'user_id' => $this->auth->id,
                'money' => $draw_price,
                'before' => $this->auth->money,
                'after' => $user->money,
                'memo' => '绘画消费',
            ]);
            // 扣除用户余额
        }

        $DrawAI = new DrawAI($draw_type);

        $result = $DrawAI->start_task([
            'prompt' => $prompt
        ]);
        if($result['status'] === 1) {
            // 保存到数据库
            $drawContent = new drawContentModel();
            $drawContent->user_id = $this->auth->id;
            $drawContent->title = $content;
            $drawContent->prompt = $prompt; // 指令
            $drawContent->message_id = $result['id'];
            $drawContent->type = $draw_type;
            $drawContent->save();
            $this->success('请求成功', $drawContent);
        } else {
            $this->error($result['msg']??'请求失败');
        }
    }

    // 获取绘画图片
    public function get_image(): void
    {
        $id = $this->request->get('id');
        if (empty($id)) $this->error('id不能为空');

//        try {
            // 获取绘画信息
            $drawContent = drawContentModel::where('id', $id)->find();

            if ($drawContent->is_draw === 1) {
                $this->success('获取成功', $drawContent);
            } elseif ($drawContent->is_draw === 2) {
                $this->error('绘画失败');
            }

            // 获取绘画
            $DrawAI = new DrawAI($drawContent['type']);

            $result = $DrawAI->task_detail([
                'message_id' => $drawContent['message_id']
            ]);
            if ($result['status'] === 1) {
                $drawContent->message_id = $result['id'] ?? '';
                $drawContent->image = $result['url'] ?? '';
                $drawContent->is_draw = 1;
                $drawContent->progress = $result['progress'] ?? 0;
                $drawContent->save();
                $this->success('绘画完成', $drawContent);
            } elseif ($result['status'] === 2) {
                $drawContent->is_draw = 2;
                $drawContent->save();
                $this->error($result['msg'] ?? '绘画失败!');
            } else {
                $this->success('绘画中1', $drawContent);
            }
//        } catch (\Exception $e) {
//            $this->error('错误1', $e->getMessage());
//        }
    }

    // 获取绘画列表
    public function get_list(): void
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $prompt = $this->request->get('prompt', '');
        $show_type = $this->request->get('show_type', '');
        $drawContent = drawContentModel::where('status', 1);
        if(!empty($prompt)) {
            $drawContent = $drawContent->where('title|prompt', 'like', '%'.$prompt.'%');
        }
        // 显示类型
        if($show_type === 'all') {
            $drawContent = $drawContent->where('image', '<>', '');
        } else {
            $this->auth->id = $this->auth->id ?? 0;
            $drawContent = $drawContent->where('user_id', $this->auth->id);
        }
        $drawContent = $drawContent->order('id', 'desc')->paginate([
            'list_rows'=> $limit,
            'page'=> $page,
        ]);
        $this->success('获取成功', $drawContent);
    }

    // 获取风格
    public function get_style(): void
    {
        $config = [
            'AK' => ConfigModel::where('name', 'yjai_key')->value('value'),
            'SK' => ConfigModel::where('name', 'yjai_secret')->value('value'),
        ];
        $style = new Yjai($config);
        $style = $style->get_style_list();
        if($style['status'] == 0) {
            $this->success('获取成功', $style['data']);
        }
    }
}